package com.tang.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tang.config.*;
import com.tang.dao.UserDao;
import com.tang.entity.User;
import com.tang.mapper.UserMapper;
import com.tang.pojo.Result;
import com.tang.pojo.UserLoginDTO;
import com.tang.pojo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.tang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务接口实现
 *
 * @author kancy
 * @since 2024-07-21 14:12:37
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {
    private final UserDao userDao;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public Result login(UserLoginDTO userLoginDTO) {
        User user = wxLogin(userLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();
        return Result.success(userLoginVO);


    }

    @Override
    public Result<String> setName(String username) {
        User user=userDao.getById(BaseContext.getCurrentId());
        user.setName(username);
        userDao.updateById(user);
        return Result.success();

    }

    private User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        //校验openid
        JSONObject jsonObject = JSON.parseObject(json);
        log.info("获取到微信服务器信息：{}",json);
        String openid = (String) jsonObject.get("openid");

        if (openid == null) {
            return null;
        }


        //校验是否新用户
        User user = userMapper.getByOpenId(openid);


        if (user == null) {
            //判断为新用户
            user = User.builder()
                    .openid(openid)
                    .build();
            userMapper.save(user);
        }

        return user;
    }
}